#!/usr/local/bin/php -f

<?php

require("globals.inc");
<<<<<<< HEAD
require("config.inc");
require("functions.inc");
=======
require("util.inc");
$g['booting'] = true;
>>>>>>> FETCH_HEAD

echo "Starting the {$g['product_name']} console firmware update system";

require("functions.inc");
echo ".";

<<<<<<< HEAD
if(isset($config['system']['firmware']['alturl']['enable']))
	$updater_url = "{$config['system']['firmware']['alturl']['firmwareurl']}";
else
	$updater_url = $g['update_url'];

$nanosize = "";
if ($g['platform'] == "nanobsd") {
	if (file_exists("/etc/nano_use_vga.txt"))
		$nanosize = "-nanobsd-vga-";
	else
		$nanosize = "-nanobsd-";

	$nanosize .= strtolower(trim(file_get_contents("/etc/nanosize.txt")));
	$update_filename = "latest{$nanosize}.img.gz";
} else {
	$update_filename = "latest.tgz";
}
$autoupdateurl = "{$updater_url}/{$update_filename}";
=======
$g['booting'] = false;

$d_fwupenabled_path = $g['varrun_path'] . "/fwup.enabled";
>>>>>>> FETCH_HEAD

$fp = fopen('php://stdin', 'r');

echo ".\n\n";

$shell_active = true;

echo "1) Update from a URL\n";
echo "2) Update from a local file\n";
echo "Q) Quit\n";

echo "\nPlease select an option to continue: ";

<<<<<<< HEAD
$pkg_interface = 'console';
=======
>>>>>>> FETCH_HEAD
$command = strtoupper(chop(fgets($fp)));

switch ($command) {
	case "q":
	case "quit":
		echo "\n";
		fclose($fp);
		die;
	break;
	case "1":
<<<<<<< HEAD
		echo "\nEnter the URL to the .tgz or .img.gz update file. \nType 'auto' to use {$autoupdateurl}\n> ";
=======
		echo "\nEnter the URL to the .tgz update file:\n> ";
>>>>>>> FETCH_HEAD
		$url = chop(fgets($fp));
		if(!$url) { 
			fclose($fp);
			die;
		}
<<<<<<< HEAD
		if($url == "auto") {
			$url = $autoupdateurl;
		}
		$status = does_url_exist($url);
		if($status) {
			conf_mount_rw();
			mark_subsystem_dirty('firmware');
			unlink_if_exists("/root/firmware.tgz");
			echo "\nFetching file... ";
			download_file_with_progress_bar($url, '/root/firmware.tgz');
			if(!file_exists("/root/firmware.tgz")) {
				echo "Something went wrong during file transfer.  Exiting.\n\n";
				fclose($fp);
				clear_subsystem_dirty('firmware');
				die;
			}
			$status = does_url_exist("$url.sha256");
			if($status) { 
				echo "\nFetching sha256... ";
				download_file_with_progress_bar($url . ".sha256", '/root/firmware.tgz.sha256');
				echo "\n";
			} else {
				echo "\n\nWARNING.\n";
				echo "\nCould not locate a sha256 file.  We cannot verify the download once completed.\n\n";
				echo "Do you still want to proceed with the upgrade [n]? ";
				$answer = strtoupper(chop(fgets($fp)));
				if ($answer == "Y" or $answer == "YES") {
					echo "\nContinuing upgrade...";
				} else {
					echo "\nUpgrade cancelled.\n\n";
					die;
				}
			}
			if(file_exists("/root/firmware.tgz.sha256")) {
				$source_sha256 = trim(`cat /root/firmware.tgz.sha256 | awk '{ print \$4 }'`,"\r");
				$file_sha256 = trim(`sha256 /root/firmware.tgz | awk '{ print \$4 }'`,"\r");
				echo "URL sha256: $source_sha256\n";
				echo "Downloaded file sha256: $file_sha256\n";
				if($source_sha256 <> $file_sha256) {
					echo "\n\nsha256 checksum does not match.  Cancelling upgrade.\n\n";
					unlink_if_exists("/root/firmware.tgz.sha256");
					fclose($fp);
					clear_subsystem_dirty('firmware');
					die -1;
				}
				echo "\nsha256 checksum matches.\n";
				unlink_if_exists("/root/firmware.tgz.sha256");
=======
		$status = does_url_exist($url);
		if($status) {
			conf_mount_rw();
			touch($d_fwupenabled_path);
			if(file_exists("/root/firmware.tgz"))
				unlink("/root/firmware.tgz");
			echo "\nFetching file size...\n";
			$file_size = exec("fetch -s \"$url\"");
			$file_size = trim($file_size, "\r");
			echo "\nFile size: $file_size\n";
			echo "\nFetching file...\n";
			exec("fetch -1 -w15 -a -v -o /root/firmware.tgz \"$url\"");
			if($file_size <> filesize("/root/firmware.tgz")) {
				echo "\nFile size mismatch.  Upgrade cancelled.\n\n";
				fclose($fp);
				die;
			}			
			if(!file_exists("/root/firmware.tgz")) {
				echo "Something went wrong during file transfer.  Exiting.\n\n";
				fclose($fp);
				die;
			}
			$status = does_url_exist("$url.md5");
			if($status) { 
				echo "\nFetching MD5...\n";
				exec("fetch -1 -w15 -a -v -o /root/firmware.tgz.md5 \"$url.md5\"");
			} else {
				echo "\n\nWARNING.\n";
				echo "\nCould not locate a MD5 file.  We cannot verify the download once its done.\n\n";
				sleep(15);
			}
			if(file_exists("/root/firmware.tgz.md5")) {
				$source_md5 = trim(`cat /root/firmware.tgz.md5 | awk '{ print \$4 }'`,"\r");
				$file_md5 = trim(`md5 /root/firmware.tgz | awk '{ print \$4 }'`,"\r");
				echo "URL MD5: $source_md5\n";
				echo "Downloaded file MD5: $file_md5\n";
				if($source_md5 <> $file_md5) {
					echo "\n\nMD5 checksum does not match.  Cancelling upgrade.\n\n";
					exec("rm -f /root/*.md5");
					fclose($fp);
					die -1;
				}
				echo "\nMD5 checksum matches.\n";
				exec("rm -f /root/*.md5");
>>>>>>> FETCH_HEAD
			}
			if(strstr($url,"bdiff")) {
				echo "Binary DIFF upgrade file detected...\n";
				$type = "bdiff";
<<<<<<< HEAD
			} elseif(strstr($url,"nanobsd")) {
				echo "NanoBSD upgrade file detected...\n";
				$type = "nanobsd";
			} else {
				$type = "normal";
			}
			do_upgrade("/root/firmware.tgz", $type);
			clear_subsystem_dirty('firmware');
			exit;
		}
	case "2":
		echo "\nEnter the complete path to the .tgz or .img.gz update file: ";
=======
			}
			if(strstr($url,"nanobsd")) {
				echo "NanoBSD upgrade file detected...\n";			
				$type = "nanobsd";	
			}			
			if(file_exists("/root/firmware.tgz")) {
				do_upgrade("/root/firmware.tgz", $type);
				exit;
			} else {
				echo "\nCould not download update.\n\n";
				fclose($fp);
				die -1;
			}
		}
	case "2":
		echo "\nEnter the complete path to the .tgz update file: ";
>>>>>>> FETCH_HEAD
		$path = chop(fgets($fp));
		if(!$path) {
			fclose($fp);
			die;
		}
		if(stristr($path,"bdiff"))
			$type = "bdiff";
		if(stristr($path,"nanobsd"))
			$type = "nanobsd";			
		if(file_exists($path)) {
<<<<<<< HEAD
			mark_subsystem_dirty('firmware');
			do_upgrade($path, $type);
			clear_subsystem_dirty('firmware');
=======
			touch($d_fwupenabled_path);
			do_upgrade($path, $type);
>>>>>>> FETCH_HEAD
		} else {
			echo "\nCould not find file.\n\n";
			fclose($fp);
			die -1;
		}
}

<<<<<<< HEAD
function do_upgrade($path, $type) {
	global $g, $fp;
=======
function check_for_kernel_file() {
	global $fp;
	$platform = file_get_contents("/etc/platform");
	$platform = str_replace("\n", "", $platform);
	$platform = str_replace("\r", "", $platform);
	if($platform == "embedded" or $platform == "wrap" or $platform == "nanobsd") {
		exec("echo wrap > /boot/kernel/pfsense_kernel.txt");
		echo "\n";
		return;
	}	
	if(!file_exists("/boot/kernel/pfsense_kernel.txt")) {
		echo "\nPlease select which kernel you would like to use:\n";
		echo "\n1. Non SMP kernel";
		echo "\n2. SMP kernel";
		echo "\n3. Embedded kernel (no video or keyboard)";
		echo "\n4. Developers kernel (slower performing, more debugging)\n";
		echo "\nPlease enter a number [1-4]: ";
		$selection = strtoupper(chop(fgets($fp)));
		switch ($selection) {
			case "1":
				exec("echo UP > /boot/kernel/pfsense_kernel.txt");
			break;
			case "2":
				exec("echo SMP > /boot/kernel/pfsense_kernel.txt");
			break;
			case "3":
				exec("echo wrap > /boot/kernel/pfsense_kernel.txt");
			break;
			case "4":
				exec("echo Developers > /boot/kernel/pfsense_kernel.txt");
			break;		
		}
		echo "\n";
	}
}

function do_upgrade($path, $type) {
	global $g, $fp, $d_fwupenabled_path;
>>>>>>> FETCH_HEAD
	
	$sigchk = verify_digital_signature($path);
	if ($sigchk == 1)
		$sig_warning = "The digital signature on this image is invalid.";
	else if ($sigchk == 2)
		$sig_warning = "This image is not digitally signed.";
	else if (($sigchk == 3) || ($sigchk == 4))
		$sig_warning = "There has been an error verifying the signature on this image.";
	if($sig_warning) {
		$sig_warning = "\nWARNING! ACHTUNG! DANGER!\n\n{$sig_warning}\n\n" .
			"This means that the image you uploaded is not an official/supported image and\n" .
			"may lead to unexpected behavior or security compromises.\n\n" .
			"Only install images that come from sources that you trust, and make sure\n".
			"that the image has not been tampered with.\n\n".
			"Do you want to install this image anyway at your own risk [n]?";
		echo $sig_warning;
		$command = strtoupper(chop(fgets($fp)));
		if(strtoupper($command) == "Y" or strtoupper($command) == "Y" or strtoupper($command) == "YES") {
			echo "\nContinuing upgrade...";
		} else {
			echo "\nUpgrade cancelled.\n\n";
			die;
		}
	}
<<<<<<< HEAD
	mark_subsystem_dirty('firmwarelock');
	echo "\nOne moment please...\nInvoking firmware upgrade...";
	if($type == "bdiff")
		mwexec_bg("/etc/rc.firmware delta_update $path");
	elseif($type == "nanobsd")
=======
	touch($d_fwupenabled_path);
	check_for_kernel_file();
	echo "\nOne moment please...\nInvoking firmware upgrade...";
	if($type == "bdiff") 
		mwexec_bg("/etc/rc.firmware delta_update $path");
	elseif($type == "nanobsd") 
>>>>>>> FETCH_HEAD
		mwexec_bg("/etc/rc.firmware pfSenseNanoBSDupgrade $path");
	else
		mwexec_bg("/etc/rc.firmware pfSenseupgrade $path");
	sleep(10);
<<<<<<< HEAD
	while(is_subsystem_dirty('firmwarelock')) {
=======
	while(file_exists($d_fwupenabled_path)) {
>>>>>>> FETCH_HEAD
		sleep(1);
		echo ".";
	}
	sleep(10);
	echo "Done.  Rebooting...\n\n";
<<<<<<< HEAD
	clear_subsystem_dirty('firmwarelock');
}

exec("rm -f /root/*.sha256");
fclose($fp);

?>
=======
	unlink_if_exists($d_fwupenabled_path);
}

exec("rm -f /root/*.md5");
fclose($fp);

?>
>>>>>>> FETCH_HEAD
